import { getCookie, setCookie, removeCache, sessionGet } from '../cache'
import { logout } from '@/api/login'

const user = {
  // 首先声明一个状态 state
  state: {
    username: getCookie('login-username'),
    mobile: getCookie('login-mobile'),
    token: getCookie('login-token'),
    avatar: getCookie('login-avatar'),
    login_id: getCookie('login-id'),
    roles: 0
  },

  // 然后给 actions 注册一个事件处理函数，当这个函数被触发时，将状态提交到 mutaions中处理
  actions: {

    // 获取用户信息
    getUserInfo({ commit }, aData) {
      commit('SET_LOGIN_INFO', aData)
    },

    // 登出  引入接口 api
    LogOut({ commit }) {
      return new Promise(resolve => {
        logout().then(response => {
          if (response.data.code === 0) {
            commit('LOGOUT')
            resolve()
          }
        })
      })
    },

    // 动态修改权限
    ChangeRoles({ commit }, role) {
      return new Promise(resolve => {
        commit('SET_TOKEN', role)
        // setToken(role)
        // getUserInfo(role).then(response => {
        //   const data = response.data
        //   commit('SET_ROLES', data.roles)
        //   commit('SET_NAME', data.name)
        //   commit('SET_AVATAR', data.avatar)
        //   commit('SET_INTRODUCTION', data.introduction)
        //   resolve()
        // })
      })
    }
  },

  mutations: {

    // 登陆信息
    SET_LOGIN_INFO: (state, aData) => {
      state.username = aData.username
      state.mobile = aData.mobile
      state.token = aData.token
      state.avatar = aData.avatar
      state.login_id = aData.id
      state.roles = aData.role_id
      setCookie('login-username', aData.username)
      setCookie('login-mobile', aData.mobile)
      setCookie('login-token', aData.token)
      setCookie('login-avatar', aData.avatar)
      setCookie('login-id', aData.id)
    },

    LOGOUT: (state) => {
      removeCache('login-username')
      removeCache('login-mobile')
      removeCache('login-id')
      removeCache('login-token')
      removeCache('login-avatar')
      sessionGet('buttonroutes', 1) // 移除权限
    }

  }

}

export default user
